package com.codegzy.controller;

import com.codegzy.entity.User;
import com.codegzy.service.UserService;
import com.codegzy.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public Map<String, Object> login(User user) {
        Map<String, Object> map = new HashMap<>();
        try {
            User login = userService.login(user);
            if (ObjectUtils.isEmpty(login)) {
                throw new RuntimeException("登录失败");
            }
            Map<String, String> mapToken = new HashMap<>();
            mapToken.put("name", user.getName());
            mapToken.put("age", String.valueOf(user.getAge()));
            String token = JWTUtil.getToken(mapToken, 1);
            map.put("state", true);
            map.put("msg", "认证成功");
            map.put("token", token);
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }

    @PostMapping("/test")
    public Map<String, Object> test() {
        Map<String, Object> map = new HashMap<>();
        map.put("state", true);
        map.put("msg", "认证成功");
        return map;
    }
}
